/*
 * 文 件 名:  ModifyIbatisModelFile.java
 * 版    权:  Chrhc Technologies Co., Ltd. Copyright 2015-2099,  All rights reserved
 * 描    述:  <描述>
 * 修 改 人: 姓名 xxx
 * 修改时间:  2015年11月23日
 */
package test.model;

import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

import org.apache.commons.io.FileUtils;

import com.chrhc.projects.cpub.gen.util.ColumnData;
import com.chrhc.projects.cpub.gen.util.CreateBean;

/**
 * <一句话功能简述> <功能详细描述>
 * 
 * @author 姓名 xxx
 * @version [1.0, 2015年11月23日]
 */
public class ModifyIbatisModelFile
{
    
    private CreateBean createBean;
    
    private Map config = null;
    
    private String path = System.getProperty("user.dir");
    
    public ModifyIbatisModelFile(String configName)
    {
        config = ConfigXMLReader.getconfig(path + configName);
        createBean = new CreateBean();
        String url = (String)config.get("connectionURL");
        String username = (String)config.get("userId");
        String password = (String)config.get("password");
        createBean.setMysqlInfo(url, username, password);
    }
    
    public void modifyModelFile()
        throws SQLException
    {
        String targetPackage = (String)config.get("targetPackage");
        String targetPackageMk = path + "/src/main/java/" + targetPackage.replaceAll("\\.", "/");
        System.out.println("targetPackageMk=" + targetPackageMk);
        
        List<Map> tableList = (List)config.get("tableList");
        String tableName;
        String domainObjectName;
        String content;
        String targetFileName = null;
        File packageMk = null;
        File targetFile = null;
        StringBuffer data;
        for (Map map : tableList)
        {
            tableName = (String)map.get("tableName");
            domainObjectName = (String)map.get("domainObjectName");
            
            // System.out.println("content::" + content);
            targetFileName = targetPackageMk + "/" + domainObjectName + ".java";
            packageMk = new File(targetPackageMk);
            targetFile = new File(targetFileName);
            
            Map colsMap = (Map)map.get("colsMap");
            content = getBeanFeilds(tableName, colsMap);
            
            /*
             * if (!packageMk.exists()) { packageMk.mkdirs(); }
             */
            if (!packageMk.exists())
            {
                packageMk.mkdirs();
            }
            
            content = content.replaceAll("java.lang.String", "String");
            content = content.replaceAll("java.sql.Timestamp", "Date");
            content = content.replaceAll("java.lang.Integer", "Integer");
            
            data = new StringBuffer();
            data.append("package ").append(targetPackage).append(";");
            data.append("\r\r").append("import java.util.Date;");
            if (content.indexOf("@Length") > 0)
            {
                data.append("\r").append("import org.hibernate.validator.constraints.Length;");
            }
            if (content.indexOf("@Size") > 0)
            {
                data.append("\r").append("import javax.validation.constraints.Size;");
            }
            if (content.indexOf("@NotNull") > 0)
            {
                data.append("\r").append("import javax.validation.constraints.NotNull;");
            }
            if (content.indexOf("@JsonFormat") > 0)
            {
                data.append("\r").append("import com.fasterxml.jackson.annotation.JsonFormat;");
            }
            // data.append("\r").append("import java.math.BigDecimal;");
            data.append("\r\r").append("public class ").append(domainObjectName).append(" {");
            data.append(content);
            data.append("\r").append("}");
            try
            {
                FileUtils.writeStringToFile(targetFile, data.toString());
            }
            catch (IOException e)
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
    
    public static void searchFile(File folder, Pattern regex)
    {
        File[] files = folder.listFiles();
        if (files == null)
        {
            System.err.println("不能访问" + folder.getAbsolutePath());
            return;
        }
        for (File file : files)
        {
            if (file.isDirectory())
            {
                searchFile(file, regex);
                
            }
            else
            {
                if (regex.matcher(file.getName()).matches())
                {
                    System.out.println(file.getAbsolutePath());
                }
            }
        }
    }
    
    public static void searchFile(String path, String regex)
    {
        searchFile(new File(path), Pattern.compile(regex));
    }
    
    public String getBeanFeilds(String tableName, Map colsMap)
        throws SQLException
    {
        List<ColumnData> dataList = createBean.getColumnDatas(tableName);
        StringBuffer str = new StringBuffer();
        StringBuffer getset = new StringBuffer();
        for (ColumnData d : dataList)
        {
            String name = d.getColumnName();
            String type = d.getDataType();
            String comment = d.getColumnComment();
            String nullable = d.getNullable();
            String cMaxLen = d.getCharmaxLength();
            List<String> annos = null;
            Map colMap = (Map)colsMap.get(name);
            if (colMap != null)
            {
                annos = (List)colMap.get("annos");
            }
            name = reName(name);// 把库的字段名称改成pojo的字段名称
            String maxChar = name.substring(0, 1).toUpperCase();
            
            // str.append("\r\r\t").append("//").append(cMaxLen + " ").append(nullable).append(";");
            boolean ifAnno = false;
            
            if (nullable.equals("N"))
            {
                str.append("\r\r\t").append("@NotNull");
                ifAnno = true;
            }
            if (annos != null)
            {
                for (String anno : annos)
                {
                    if (ifAnno)
                    {
                        str.append("\r\t");
                    }
                    else
                    {
                        str.append("\r\r\t");
                    }
                    str.append(anno);
                    ifAnno = true;
                }
            }
            
            if (cMaxLen != null && !cMaxLen.equals(""))
            {
                if (ifAnno)
                {
                    str.append("\r\t");
                }
                else
                {
                    str.append("\r\r\t");
                }
                str.append("@Size(max=").append(cMaxLen).append(")");
                ifAnno = true;
            }
            if (ifAnno)
            {
                str.append("\r\t");
            }
            else
            {
                str.append("\r\r\t");
            }
            str.append("private ").append(type + " ").append(name).append(";//   ").append(comment);
            String method = maxChar + name.substring(1, name.length());
            
            getset.append("\r\r\t").append("public ").append(type + " ").append("get" + method + "() {\r\t");
            getset.append("    return this.").append(name).append(";\r\t}");
            
            getset.append("\r\r\t").append("public void ").append("set" + method + "(" + type + " " + name + ") {\r\t");
            getset.append("    this." + name + " = ").append(name);
            if (type.equals("java.lang.String"))
            {
                getset.append(" == null ? null : ").append(name).append(".trim()");
            }
            
            getset.append(";\r\t}");
        }
        
        return str.toString() + getset.toString();
    }
    
    private String reName(String name)
    {
        String arr[] = name.split("_");
        int i = 0;
        StringBuffer buf = new StringBuffer();
        for (String s : arr)
        {
            if (i > 0)
            {
                buf.append(s.substring(0, 1).toUpperCase() + s.substring(1));
            }
            else
            {
                buf.append(s);
            }
            i++;
        }
        return buf.toString();
    }
    
    /**
     * <一句话功能简述> <功能详细描述>
     * 
     * @param args
     */
    public static void main(String[] args)
    {
        // TODO Auto-generated method stub
        String configName = "/src/main/resource/conf/generatorConfig-message.xml";
        // String configName = "/src/main/resource/conf/generatorConfig-netservice.xml";
        ModifyIbatisModelFile modify = new ModifyIbatisModelFile(configName);
        try
        {
            modify.modifyModelFile();
        }
        catch (SQLException e)
        {
            e.printStackTrace();
        }
        
    }
}
